package chapter3.lc215;

import java.util.Arrays;
//LC 215 第K大元素 （就是第N-K小）
public class KthLargestElement {
    public int findKthLargest(int[] nums, int k) {
        int left = 0;
        int right = nums.length -1;
        int target = nums.length - k;

        // index = partition（left ，right）
        // 类似二分的做法，如果index < target 则丢掉index左边 反之则丢掉index右边
        while (true) {
            int index = partition(nums, left, right);
            if (index == target) {
                return nums[index];
            }else if(index < target) {
                left = index + 1;
            }else {
                right = index - 1;
            }
        }
    }
    //返回整数nums[left]，在区间[left, right]排序后的index
    //[left + 1, index] < nums[left]
    //[index + 1, right] >= nums[left]
    private int partition(int[] nums, int left, int right) {
        int pivot = nums[left];
        int j = left;
        // 双指针swap
        for (int i = left + 1; i <= right; i++) {
            if (nums[i] < pivot) {
                j++;
                swap(nums, i, j);
            }
        }
        // 把pivot放到正确的位置
        swap(nums, j, left);
        return j;
    }

    private void swap(int[] nums, int i, int j) {
        if (i == j) return;
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{5,4,5,1,3,5,9,2,3,7,12,4};
        int index = new KthLargestElement().partition(nums, 1, nums.length -1);
        System.out.println(Arrays.toString(nums));
        System.out.println(index);
    }

}
